<template>
  <component :is="SvgComponent" :style="svgDefaultStyle" :class="props.class" />
</template>

<script lang="ts" setup>
import type { SvgIconProps } from "../type";
import { shallowRef, defineAsyncComponent, onMounted, watch } from "vue";

const props = withDefaults(defineProps<SvgIconProps>(), {
  name: "",
  style: undefined,
  class: undefined
});

const SvgComponent = shallowRef(null);
const svgModules = import.meta.glob("@/assets/svg/*.svg");
const svgIconMap: Record<string, () => Promise<any>> = {};
const svgDefaultStyle = !props.class ? Object.assign({ width: "1em", height: "1em" }, props.style) : props.style;
const initSvgIcon = (name: string) => {
  if (!svgIconMap[name]) {
    console.error(`${name} 图标未找到`);
    return null;
  }
  // 动态加载 svg 图标
  SvgComponent.value = defineAsyncComponent(svgIconMap[name]);
};

watch(
  () => props.name,
  newName => {
    initSvgIcon(newName);
  }
);

onMounted(() => {
  Object.keys(svgModules).forEach(path => {
    const iconName = path.replace("/src/assets/svg/", "").replace(".svg", "");
    svgIconMap[iconName] = svgModules[path];
  });

  initSvgIcon(props.name);
});
</script>
